{% extends "app/base_site.html" %}

{% block title %}  查看训练 {% endblock title %}

{% block stylesheets %}
  {{ block.super }}
<style>
    .xc_log_panel{
                    flex: 1;
                background: black;
                color: #00ff00;
                padding: 0;
                border-radius: 6px;
                height: 580px;
                overflow-y: auto;
    }
    .xc_log_panel>pre {
        background: black;
        color: #00ff00;

    }

  .custom-file-upload {
    color: #fff;
    display: inline-block;
    padding: 5px 10px;
    cursor: pointer;
      background: #0960bd;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
    border-radius: 4px;
  }
.custom-file-upload:hover{
    background: #0D3349;
}
  .custom-file-upload > span {
      font-size: 12px;
  }

  .custom-file-upload > input {
    display: none;
  }
</style>
{% endblock stylesheets %}

{% block content %}

  <div class="right_col" role="main">
    <div class="">
      <div class="row">
        <!-- 查看训练start -->
        <div class="col-md-6 col-sm-6 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
              <h2>查看训练</h2>
              <div class="clearfix"></div>
            </div>
            <div class="x_content">
                <div class="form-horizontal form-label-left">
                        <!--
                        <p>For alternative validation library <code>parsleyJS</code> check out in the <a href="form.html">form page</a>
                        </p>
                        <span class="section">Personal Info</span>
                        -->
                          <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练编号
                          </label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                                <input type="text" readonly  value="{{ train_code }}" required="required" class="form-control col-md-6 col-xs-12">
                              </div>
                            </div>


                        <div class="item form-group">
                              <label class="control-label col-md-3 col-sm-3 col-xs-12" >选择任务 <span class="required" style="color: red;">*</span>
                              </label>
                            <div class="col-md-6 col-sm-6  col-xs-12">
                                     <select disabled id="select_task" class="select2_single form-control" required="required">
                                       <option value="{{ train.task_code }}">{{ train.task_code }}</option>
                                     </select>
                              </div>
                        </div>

                       <div class="item form-group">
                              <label class="control-label col-md-3 col-sm-3 col-xs-12" >选择算法 <span class="required" style="color: red;">*</span>
                              </label>
                            <div class="col-md-6 col-sm-6  col-xs-12">

                                 <select disabled id="select_algorithm" class="select2_single form-control" required="required">
                                       <option value="{{ train.algorithm_code }}">{{ train.algorithm_code }}</option>
                                 </select>

                              </div>
                        </div>

                          <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">推理设备 <span class="required" style="color: red;">*</span>
                          </label>
                        <div class="col-md-6 col-sm-6  col-xs-12">
                                     <input type="text" readonly id="device"  value="{{ train.device }}" required="required" class="form-control col-md-6 col-xs-12">

                          </div>
                        </div>

                                                          <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12" >输入尺寸 <span class="required" style="color: red;">*</span>
                          </label>
                        <div class="col-md-6 col-sm-6  col-xs-12">

                            <input readonly type="number" id="imgsz"  value="{{ train.imgsz }}" required="required" class="form-control col-md-6 col-xs-12">

                          </div>
                        </div>


                        <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练周期 <span class="required" style="color: red;">*</span>
                          </label>
                        <div class="col-md-6 col-sm-6  col-xs-12">

                            <input type="number" readonly id="epochs"  value="{{ train.epochs }}" required="required" class="form-control col-md-6 col-xs-12">

                          </div>
                        </div>

                        <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练批次 <span class="required" style="color: red;">*</span>
                          </label>
                        <div class="col-md-6 col-sm-6  col-xs-12">

                            <input type="number" readonly id="batch"  value="{{ train.batch }}" required="required" class="form-control col-md-6 col-xs-12">

                          </div>
                        </div>

                                        <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">保存周期 <span class="required" style="color: red;">*</span>
                          </label>
                        <div class="col-md-6 col-sm-6  col-xs-12">

                            <input type="number" readonly id="save_period"  value="{{ train.save_period }}" required="required" class="form-control col-md-6 col-xs-12">

                          </div>
                        </div>

                          <div class="item form-group">
                              <label class="control-label col-md-3 col-sm-3 col-xs-12" >训练比 <span class="required" style="color: red;">*</span>
                              </label>
                            <div class="col-md-6 col-sm-6  col-xs-12">

                                <input type="number" readonly id="sample_ratio"  value="{{ train.sample_ratio }}" required="required" class="form-control col-md-6 col-xs-12">

                              </div>
                        </div>

                        <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">其他参数
                          </label>
                        <div class="col-md-6 col-sm-6  col-xs-12">
                                <textarea readonly rows="3" id="extra" class="form-control col-md-6 col-xs-12" placeholder="其他参数">{{ train.extra }}</textarea>

                          </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-3">

                        {% if train.train_count > 0 %}
                                <button type="button" onclick="f_postTaskStartTrain()" class="btn btn-primary btn-sm">重新训练</button>
                            {% else %}
                                <button type="button" onclick="f_postTaskCreateDatasets()" class="btn btn-primary btn-sm">生成训练集</button>
                                <button type="button" onclick="f_postTaskStartTrain()" class="btn btn-primary btn-sm">开始训练</button>
                               {% endif %}
                                <button type="button" onclick="f_postTaskStopTrain()" class="btn btn-default btn-sm">停止训练</button>

                          </div>
                        </div>
                        <div class="item form-group">
                             <div class="col-md-6 col-md-offset-3">
                                <span id="train_loading" style="display: none;"><img class="top_loading_img" src="/static/images/load.gif" alt="loading">执行中</span>
                              </div>
                        </div>
                </div>
            </div>
          </div>
        </div>
        <!-- 查看训练end -->

        <!-- 显示训练日志窗口start -->
        <div class="col-md-6 col-sm-6 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
              <h2>训练日志</h2>
              <div class="clearfix"></div>
            </div>
            <div class="x_content">
                    <div class="xc_log_panel">
                            <pre style="display: none;" id="xc_train_pre"></pre>
                    </div>
            </div>
          </div>
        </div>
        <!-- 显示训练日志窗口end -->

        <!-- 显示模型训练参数start -->
          <div class="col-md-6 col-sm-6 col-xs-12">
            <div class="x_panel">
            <div class="x_title">
              <h2>模型训练参数</h2>
              <div class="clearfix"></div>
            </div>
              <div class="x_content">
               <div class="form-horizontal form-label-left">


                                           <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练状态
                          </label>
                        <div class="col-md-6 col-sm-6  col-xs-12">
                            {% if train.train_state == 1 %}
                            <p style="color: red">训练中 <img class="top_loading_img" src="/static/images/load.gif" alt="loading"></p>
                                {% elif train.train_state == 2 %}
                                     <p style="color: green">已完成</p>
                            {% else %}
                            <p>未训练</p>
                            {% endif %}
                          </div>
                        </div>


           {% if  train.train_datasets_time != None %}
               <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练集生成时间
                          </label>
                 <div class="col-md-6 col-sm-6  col-xs-12">
                            <p>{{ train.train_datasets_time }}</p>
                          </div>
                        </div>
           {% endif %}
            {% if  train.train_datasets_remark != "" %}
                          <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练集描述
                          </label>
                    <div class="col-md-6 col-sm-6  col-xs-12">
                        <p>{{ train.train_datasets_remark }}</p>
                    </div>
                </div>
           {% endif %}
            {% if  train.train_datasets != "" %}
                      <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练集
                          </label>
                 <div class="col-md-6 col-sm-6  col-xs-12">
                      <textarea style="overflow:hidden;border: none;" rows="3" class="form-control col-md-6 col-xs-12" >{{ train.train_datasets }}</textarea>

                          </div>
                        </div>
                {% endif %}

                {% if  train.train_command != "" %}
                      <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练命令行
                          </label>
                 <div class="col-md-6 col-sm-6  col-xs-12">
                      <textarea style="overflow:hidden;border: none;" rows="8" class="form-control col-md-6 col-xs-12" >{{ train.train_command }}</textarea>

                          </div>
                        </div>
                {% endif %}

                                                  <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练总次数
                          </label>
                <div class="col-md-6 col-sm-6  col-xs-12">
                            <p>{{ train.train_count}}</p>
                          </div>
                        </div>
                {% if  train.train_pid > 0 %}
                                <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练进程ID
                          </label>
                      <div class="col-md-6 col-sm-6  col-xs-12">
                            <p>{{ train.train_pid}}</p>
                          </div>
                        </div>
               {% endif %}

            {% if  train.train_start_time != None %}
                                 <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练开始时间
                          </label>
              <div class="col-md-6 col-sm-6  col-xs-12">
                            <p>{{ train.train_start_time }}</p>
                          </div>
                        </div>
               {% endif %}
            {% if  train.train_stop_time != None %}
                          <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练结束时间
                          </label>
                 <div class="col-md-6 col-sm-6  col-xs-12">
                            <p>{{ train.train_stop_time }}</p>
                          </div>
                        </div>
                {% endif %}

                    {% if  train_best_model_filepath != "" %}
                         <div class="item form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">训练结果
                          </label>
                          <div class="col-md-6 col-sm-6  col-xs-12">

                               <textarea style="overflow:hidden;border: none;" rows="3" class="form-control col-md-6 col-xs-12" >{{ train_best_model_filepath }}</textarea>
                           </div>
                           </div>
                {% endif %}
                    </div>
              </div>
            </div>
          </div>
        <!-- 显示模型训练参数end -->

              <!-- 显示模型测试记录start -->
          <div class="col-md-6 col-sm-6 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                  <h2>模型测试记录
                   <span id="test_model_loading" style="display: none;"><img class="top_loading_img" src="/static/images/load.gif" alt="loading">测试中</span>
                  </h2>
                  <div class="clearfix"></div>
                </div>
                <div class="x_content">
                        <div class="form-horizontal form-label-left">
                                   <div class="form-group">
                                       <div style="margin-left: 5px;">
                                           <label class="custom-file-upload">
                                            <span><i class="fa fa-image"></i> 测试图片</span>
                                                <input type="file" name="file_image" accept="image/png,image/jpeg,image/jpg" placeholder="图片文件" onchange="f_upload_file_image()">
                                          </label>
                                            <label class="custom-file-upload">
                                                <span><i class="fa fa-video-camera"></i> 测试视频</span>
                                                 <input type="file" name="file_video"  accept="video/*"  placeholder="视频文件"  onchange="f_upload_file_video()">
                                              </label>
                                       </div>
                                  </div>
                        </div>
                        <table class="table table-striped projects">
                                <thead>
                                  <tr>
                                    <th>ID</th>
                                    <th>创建用户</th>
                                    <th>文件名</th>
                                    <th>查看</th>
                                    <th>效果</th>
                                    <th>耗时</th>
                                    <th>时间</th>
                                    <th>操作</th>
                                  </tr>
                                </thead>
                                <tbody id="testModelData">
                                    <tr class="even pointer"><td colspan='8'>暂无数据</td></tr>
                                </tbody>
                            </table>
                </div>

            </div>
          </div>
        <!-- 显示模型测试记录end -->
      </div>
    </div>
  </div>

{% endblock content %}

{% block javascripts %}
  {{ block.super }}

<script>
    let mTrainCode = "{{ train_code }}";
    let storageDir_www = "{{ storageDir_www }}";
    let eleTrainLoading = $("#train_loading");
    let eleTestModelLoading = $("#test_model_loading");
    let eleJsXcTrainPre = document.getElementById('xc_train_pre');
    let eleSelectTask = $("#select_task");// select  选择任务
    let eleSelectAlgorithm = $("#select_algorithm");// select  选择任务
    let eleInputFileImage= $("input[name='file_image']");
    let eleInputFileVideo= $("input[name='file_video']");
    let eleTestModelData = $("#testModelData");

    let temp_train_log_index = 0;

    eleSelectTask.change(function () {
        temp_train_log_index = 0;
        eleJsXcTrainPre.style.display = "none";
        eleJsXcTrainPre.textContent = '';
    });
function f_openImg(imgUrl) {
    window.open(imgUrl)
}
function f_postTaskCreateDatasets() {
            eleTrainLoading.show();
        $.ajax({
               url: '/train/postTaskCreateDatasets',
               type: "post",
               async: true,
               data: {"train_code":mTrainCode},
               dataType: "json",
               timeout: 0,
               error: function () {
                   eleTrainLoading.hide();
                   myAlert("网络异常，请确定网络正常！","error");

               },
               success: function (res) {

                   eleTrainLoading.hide();
                   if(1000 === res.code){
                        myAlert(res.msg,"success",1000);
                        setTimeout(function() {
                           window.location.reload();
                        }, 1000);

                   }else{
                        myAlert(res.msg,"error");
                   }
               }
            });
}
function f_postTaskStartTrain() {

        eleTrainLoading.show();
        $.ajax({
               url: '/train/postTaskStartTrain',
               type: "post",
               async: true,
               data: {"train_code":mTrainCode},
               dataType: "json",
               timeout: 0,
               error: function () {
                   eleTrainLoading.hide();
                   myAlert("网络异常，请确定网络正常！","error");

               },
               success: function (res) {

                   eleTrainLoading.hide();
                   if(1000 === res.code){
                        myAlert(res.msg,"success",1000);
                        setTimeout(function() {
                           window.location.reload();
                        }, 1000);

                   }else{
                        myAlert(res.msg,"error");
                   }
               }
            });

}
function f_postTaskStopTrain() {
        eleTrainLoading.show();
        $.ajax({
               url: '/train/postTaskStopTrain',
               type: "post",
               async: true,
               data: {"train_code":mTrainCode},
               dataType: "json",
               timeout: 0,
               error: function () {
                   eleTrainLoading.hide();
                   myAlert("网络异常，请确定网络正常！","error");

               },
               success: function (res) {

                   eleTrainLoading.hide();
                   if(1000 === res.code){
                        myAlert(res.msg,"success",1000);
                        setTimeout(function() {
                           window.location.reload();
                        }, 1000);
                   }else{
                        myAlert(res.msg,"error");
                   }
               }
            });

}
function f_getTrainLog() {
    let task_code = eleSelectTask.val().trim();//typeof string

    if(task_code==="-1"){
            setTimeout(function() {
                  f_getTrainLog();
                }, 6000);
        return;
    }else if(task_code==="0"){
            setTimeout(function() {
                  f_getTrainLog();
                }, 6000);
        return;
    }

    $.ajax({
           url: '/train/getTrainLog',
           type: "get",
           async: true,
           data: {"task_code":task_code,"train_code":mTrainCode,"train_log_index":temp_train_log_index},
           dataType: "json",
           timeout: 0,
           error: function () {
            setTimeout(function() {
                  f_getTrainLog();
                }, 6000);

           },
           success: function (res) {
               if(1000 === res.code){

                   eleJsXcTrainPre.style.display = "block";

                   let log_lines = res.log_lines;
                   for (let i = 0; i < log_lines.length; i++) {
                       eleJsXcTrainPre.textContent += log_lines[i];
                       // 自动滚动到底部
                       eleJsXcTrainPre.parentElement.scrollTop = eleJsXcTrainPre.parentElement.scrollHeight;
                       temp_train_log_index += 1;
                   }
               }else{

               }

            setTimeout(function() {
                  f_getTrainLog();
                }, 6000);

           }
        });


}
function f_trainTest_getIndex() {
    eleTestModelLoading.show()
    $.ajax({
           url: '/trainTest/getIndex',
           type: "get",
           async: true,
           data: {"train_code":mTrainCode},
           dataType: "json",
           timeout: 0,
           error: function () {
               eleTestModelLoading.hide()
               myAlert("网络异常，请确定网络正常！","error");
           },
           success: function (res) {
               eleTestModelLoading.hide()
               eleTestModelData.html("");
               if(res.code === 1000){
                   let data = res.data;
                   let data_length = data.length;
                   let item_html;

                   if(data_length === 0){
                        item_html = "";
                        item_html += "<tr class=\"even pointer\">";
                        item_html += "<td colspan='8'>暂无数据</td>";
                        item_html += "</tr>";
                        eleTestModelData.append(item_html);
                   }else{
                       for (let i = 0; i < data.length; i++) {
                           let file_type = data[i]["file_type"];
                           let file_name = data[i]["file_name"];


                           item_html = "";
                           item_html +="<tr><td>"+data[i]["id"]+"</td>";
                           item_html +="<td>"+data[i]["username"]+"</td>";
                           item_html +="<td>"+file_name+"</td>";
                           if(file_type === 1){
                               let sourceUrl = storageDir_www + "train/"+data[i]["train_code"]+"/test/"+data[i]["code"]+"/"+file_name;
                               let resultUrl = storageDir_www + "train/"+data[i]["train_code"]+"/test/"+data[i]["code"]+"/predict/"+file_name;

                               item_html +="<td><img onclick='f_openImg(\""+sourceUrl+"\")' src=\""+sourceUrl+"\" class=\"avatar\" style='cursor: pointer' alt=\"Avatar\"></td>";
                                item_html +="<td><img onclick='f_openImg(\""+resultUrl+"\")' src=\""+resultUrl+"\" class=\"avatar\" style='cursor: pointer' alt=\"Avatar\"></td>";
                           }else if(file_type === 2){
                               let predict_file_name = file_name.slice(0,file_name.length - 3) + "avi";
                               let sourceUrl = storageDir_www + "train/"+data[i]["train_code"]+"/test/"+data[i]["code"]+"/"+file_name;
                               let resultUrl = storageDir_www + "train/"+data[i]["train_code"]+"/test/"+data[i]["code"]+"/predict/"+predict_file_name;
                                item_html +="<td><a target='_blank' href='"+sourceUrl+"' >在线播放</a></td>";
                                item_html +="<td><a target='_blank' href='"+resultUrl+"'  >下载</a></td>";
                           }else{
                                item_html +="<td></td>";
                                item_html +="<td></td>";
                           }
                            item_html +="<td>"+data[i]["calcu_seconds"]+"(s)</td>";
                            item_html +="<td>"+data[i]["create_time_str"]+"</td>";
                           item_html +="<td><a href=\"javascript:f_trainTest_postDel('"+data[i]["code"]+"')\" class=\"btn btn-danger btn-xs\"><i class=\"fa fa-trash-o\"></i></a></td>";
                           item_html +="</tr>";
                            eleTestModelData.append(item_html);
                       }

                   }
               }
           }
        });
}
function f_trainTest_postDel(test_code){
        eleTestModelLoading.show();
        $.ajax({
               url: '/trainTest/postDel',
               type: "post",
               async: true,
               data: {"code":test_code},
               dataType: "json",
               timeout: 0,
               error: function () {
                   eleTestModelLoading.hide();
                   myAlert("网络异常，请确定网络正常！","error");
               },
               success: function (res) {
                      eleTestModelLoading.hide();
                   if(1000 === res.code){
                        window.location.reload();
                   }else{
                        myAlert(res.msg,"error");
                   }
               }
            });

    }
function f_trainTest_postAdd(formData){
    eleTestModelLoading.show();
   $.ajax({
       url: "/trainTest/postAdd",
       type: "post",
       async: true,
       contentType:false,
       processData:false,
       data: formData,
       dataType: "json",
       timeout: 0,
       error: function () {
             eleTestModelLoading.hide();
           myAlert("网络异常，请确定网络正常！","error");
       },
       success: function (res) {
             eleTestModelLoading.hide();
           if(res.code === 1000){
               window.location.reload();
           }else{
               myAlert(res.msg,"error");
           }
       }
   });

}
function f_upload_file_image() {
    let file_len = eleInputFileImage[0].files.length;
       if(file_len  === 1){
           let formData = new FormData();
           formData.append("train_code",mTrainCode);
           formData.append("file_type",1);//0:未知 1:图片 2:视频

           for (let i = 0; i < file_len; i++) {
               let file = eleInputFileImage[0].files[i];
               let fs_name = file.name;
               let fs_size = parseInt(file.size);//文件字节大小
               let fs_size_m = parseInt(fs_size / 1024 / 1024); //换算成M单位

               formData.append("file"+i.toString(),file);
           }
           f_trainTest_postAdd(formData);

       }else{
           myAlert("请选择一个图片文件","error");
           return false;
       }

}
function f_upload_file_video() {
    let file_len = eleInputFileVideo[0].files.length;
       if(file_len === 1){
           let formData = new FormData();
           formData.append("train_code",mTrainCode);
           formData.append("file_type",2);//0:未知 1:图片 2:视频

           for (let i = 0; i < file_len; i++) {
               let file = eleInputFileVideo[0].files[i];
               let fs_name = file.name;
               let fs_size = parseInt(file.size);//文件字节大小
               let fs_size_m = parseInt(fs_size / 1024 / 1024); //换算成M单位

               formData.append("file"+i.toString(),file);
           }
           f_trainTest_postAdd(formData);
       }else{
           myAlert("请选择一个视频文件","error");
           return false;
       }
}

$(function() {
    f_getTrainLog();
    f_trainTest_getIndex();
});

</script>

{% endblock javascripts %}

